"""
Python wrapper for the intermediate code generation.
This module provides access to print_instruction_test.exe for generating intermediate code.
"""

import os
import sys
import tempfile
import subprocess

# 根目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# 解析器目录
PARSER_DIR = os.path.join(BASE_DIR, 'parser')

# 可执行文件路径
PRINT_INSTRUCTION_EXE = os.path.join(PARSER_DIR, 'print_instruction_test.exe')

def generate_intermediate_code(code):
    """
    生成C代码的中间代码并返回结果
    
    参数:
        code (str): 要分析的C代码字符串
        
    返回:
        tuple: (success, result, error_message)
            success (bool): 是否成功生成
            result (str): 生成的中间代码结果
            error_message (str): 错误信息（如果有）
    """
    print(f"开始生成中间代码...")
    print(f"PRINT_INSTRUCTION_EXE路径: {PRINT_INSTRUCTION_EXE}")
    print(f"exe文件存在: {os.path.exists(PRINT_INSTRUCTION_EXE)}")
    
    if not os.path.exists(PRINT_INSTRUCTION_EXE):
        error_msg = f"找不到print_instruction_test.exe: {PRINT_INSTRUCTION_EXE}"
        print(error_msg)
        return False, None, error_msg
    
    try:
        # 创建临时文件保存代码
        with tempfile.NamedTemporaryFile(suffix='.c', delete=False, mode='w', encoding='utf-8') as temp_file:
            temp_file_path = temp_file.name
            temp_file.write(code)
        
        # 获取exe所在目录
        exe_dir = os.path.dirname(PRINT_INSTRUCTION_EXE)
        exe_name = os.path.basename(PRINT_INSTRUCTION_EXE)
        
        print(f"exe目录: {exe_dir}")
        print(f"exe名称: {exe_name}")
        print(f"临时文件: {temp_file_path}")
        print(f"exe目录存在: {os.path.exists(exe_dir)}")
        print(f"exe在目录中存在: {os.path.exists(os.path.join(exe_dir, exe_name))}")
        
        # 使用绝对路径调用exe
        print(f"准备执行命令: {PRINT_INSTRUCTION_EXE} {temp_file_path}")
        result = subprocess.run(
            [PRINT_INSTRUCTION_EXE, temp_file_path], 
            capture_output=True, 
            text=True,
            timeout=30,  # 30秒超时
            encoding='utf-8'
        )
        
        print(f"命令执行完成，返回码: {result.returncode}")
        
        # 删除临时文件
        try:
            os.unlink(temp_file_path)
        except:
            pass
        
        if result.returncode == 0:
            # 成功执行
            output = result.stdout if result.stdout else "中间代码生成完成，但没有输出内容"
            return True, output, None
        else:
            # 执行失败
            error_msg = result.stderr if result.stderr else "未知错误"
            return False, None, f"生成失败，返回码: {result.returncode}, 错误信息: {error_msg}"
            
    except subprocess.TimeoutExpired:
        error_msg = "中间代码生成超时（超过30秒）"
        print(error_msg)
        return False, None, error_msg
    except Exception as e:
        error_msg = f"调用print_instruction_test.exe失败: {str(e)}"
        print(error_msg)
        return False, None, error_msg

# 测试代码
if __name__ == "__main__":
    test_code = """
int main() {
    int a;
    a = 1 > 2 ? 0 : 0;
    printf("%d", a);
}
    """
    
    success, result, error = generate_intermediate_code(test_code)
    if success:
        print("生成成功:")
        print(result)
    else:
        print(f"生成失败: {error}")
